import type {
  ExecutionContext,
  NestInterceptor,
  CallHandler,
} from '@nestjs/common';
import type { Observable } from 'rxjs';
import { map } from 'rxjs';
import { Injectable } from '@nestjs/common';
import { format } from 'date-fns';

/**
 * 拦截器 成功返回的统一响应格式
 */
@Injectable()
export class ResponseIntercept implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    const request = context.switchToHttp().getRequest<Request>();
    return next
      .handle()
      .pipe(
        map((data) => {
          const traverse = (obj) => {
            if (Array.isArray(obj)) {
              return obj.map(traverse);
            } else if (obj && typeof obj === 'object') {
              // 时间格式化
              if (obj.createTime) {
                obj.createTime = format(obj.createTime, 'yyyy-MM-dd HH:mm:ss');
              }
              if (obj.updateTime) {
                obj.updateTime = format(obj.updateTime, 'yyyy-MM-dd HH:mm:ss');
              }
              return obj;
            }
            return obj;
          };
          return traverse(data);
        }),
      )
      .pipe(
        map((data) => {
          return {
            code: 0,
            msg: data?.msg !== undefined ? data.msg : '成功',
            traceId: request['traceId'],
            data: data,
          };
        }),
      );
  }
}
